package com.nitty.cash.loop.ui.adapter

import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.recyclerview.widget.RecyclerView
import com.lib.common.adapter.CommonRecyclerViewAdapter
import com.lib.common.adapter.CommonViewHolderHelper
import com.lib.common.shapeview.layout.ShapeRelativeLayout
import com.nitty.cash.loop.R
import com.nitty.cash.loop.configs.NittyConfigs
import com.nitty.cash.loop.event.NittyEventPointHelper
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import com.nitty.cash.loop.weight.font.CustomEditText
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/19 13:54
 * @Annotation：认证流程步骤适配器
 */
class ProcessGeneralAdapter(recyclerView: RecyclerView?): CommonRecyclerViewAdapter<JSONObject>(recyclerView) {
    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "DATE_PICK" ->{//出生日期选择
                return R.layout.ui_process_select_item
            }
            "GENDER_PICK" -> {//性别
                return R.layout.ui_process_gender_item
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.ui_process_mobile_item
            }
            "SELECT" -> {//选择
                return R.layout.ui_process_select_item
            }
            else -> {//输入框
                return R.layout.ui_process_input_item
            }
        }
    }

    override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.authStepSelect)//选择
        helper.setItemChildClickListener(R.id.authStepContactImage)//选择联系人
        helper.setItemChildClickListener(R.id.authStepMobile)
    }

    override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val authStepTitle = helper.getTextView(R.id.authStepTitle)
        var showTitle = model.optString("title")
        if (NittyConfigs.isSwahili()){
            showTitle = model.optString("title_sw")
        }
        authStepTitle.text = findKeywordColor(Color.parseColor("#FFFF4D3E"),showTitle,"*")

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT" ->{//时间选择、选择
                showAuthStepSelectItemView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showAuthStepContactMobileItemView(helper,position,model)
            }
            "GENDER_PICK" -> {//性别
                showAuthStepSelectGenderItemView(helper,position,model)
            }
            else -> {//输入框
                showAuthStepInputItemView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showAuthStepInputItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val authStepEdit = helper.getView<CustomEditText>(R.id.authStepEdit)
        var showHint = model.optString("hint")
        if (NittyConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        authStepEdit.setHint(showHint)
        authStepEdit.shapeDrawableBuilder
            .setSolidColor(Color.parseColor("#FFFAFAFA"))
            .intoBackground()
        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            if (selectItem != null) {
                showText = selectItem.optString("title")
            }
        }
        authStepEdit.setText(showText)
        authStepEdit.setInputFocusChangeListener(object : CustomEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }
            override fun onCompleteAction(v: View?, remark: String) {
                var eventType = String.format(NittyEventPointType.FORM.NITTY_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(NittyEventPointType.FORM.NITTY_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                NittyEventPointHelper.addEventPointRequestAction(eventType,remark)
            }
        })

        authStepEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepEdit.clearFocus()
                true
            }
            false
        }
        authStepEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 选择性别
     */
    private fun showAuthStepSelectGenderItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        val genderMaleLayout = helper.getView<ShapeRelativeLayout>(R.id.genderMaleLayout)
        genderMaleLayout.shapeDrawableBuilder
            .setSolidColor(Color.parseColor("#FFFAFAFA"))
            .intoBackground()
        val textGenderMale = helper.getTextView(R.id.textGenderMale)
        textGenderMale.setTextColor(Color.parseColor("#FF999999"))
        helper.setVisibility(R.id.imgGenderMale,View.GONE)

        val genderFemaleLayout = helper.getView<ShapeRelativeLayout>(R.id.genderFemaleLayout)
        genderFemaleLayout.shapeDrawableBuilder
            .setSolidColor(Color.parseColor("#FFFAFAFA"))
            .intoBackground()
        val textGenderFemale = helper.getTextView(R.id.textGenderFemale)
        textGenderFemale.setTextColor(Color.parseColor("#FF999999"))
        helper.setVisibility(R.id.imgGenderFemale,View.GONE)

        val values = model.optJSONArray("values")
        if (values != null){
            if (values.length() > 0){
                val item = values.optJSONObject(0)
                var showTitle = item.optString("title")
                if (NittyConfigs.isSwahili()){
                    showTitle = item.optString("title_sw")
                }
                textGenderMale.text = showTitle
            }
            if (values.length() > 1){
                val item = values.optJSONObject(1)
                var showTitle = item.optString("title")
                if (NittyConfigs.isSwahili()){
                    showTitle = item.optString("title_sw")
                }
                textGenderFemale.text = showTitle
            }
        }

        //选中
        if (model.has("selectItem")){
            val selectValue = model.getJSONObject("selectItem")
            if (values != null){
                if (values.length() > 0){
                    val item = values.optJSONObject(0)
                    if (item.optString("title") == selectValue.optString("title")){
                        genderMaleLayout.shapeDrawableBuilder
                            .setSolidColor(Color.parseColor("#FFFD5118"))
                            .intoBackground()
                        textGenderMale.setTextColor(Color.parseColor("#FFFFFFFF"))
                        helper.setVisibility(R.id.imgGenderMale,View.VISIBLE)
                    }
                }
                if (values.length() > 1){
                    val item = values.optJSONObject(1)
                    if (item.optString("title") == selectValue.optString("title")){
                        genderFemaleLayout.shapeDrawableBuilder
                            .setSolidColor(Color.parseColor("#FFFD5118"))
                            .intoBackground()
                        textGenderFemale.setTextColor(Color.parseColor("#FFFFFFFF"))
                        helper.setVisibility(R.id.imgGenderFemale,View.VISIBLE)
                    }
                }
            }
        }

        genderMaleLayout.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(0)
                model.put("selectItem", item)
                NittyEventPointHelper.addEventPointRequestAction(String.format(NittyEventPointType.CLICK.NITTY_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }

        genderFemaleLayout.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(1)
                model.put("selectItem", item)
                NittyEventPointHelper.addEventPointRequestAction(String.format(NittyEventPointType.CLICK.NITTY_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }
    }

    /**
     * 选择类型
     */
    private fun showAuthStepSelectItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (NittyConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val authStepSelectText = helper.getTextView(R.id.authStepSelectText)
        authStepSelectText.setHint(showHint)
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            var showTitle = selectItem.optString("title")
            if (NittyConfigs.isSwahili()){
                showTitle = selectItem.optString("title_sw")
            }
            authStepSelectText.text = showTitle
        }

        val authStepSelectImage = helper.getImageView(R.id.authStepSelectImage)
        authStepSelectImage.setImageResource(R.mipmap.nitty_right_black)
        when(model.optString("action")){
            "SELECT" ->{//选择
                authStepSelectImage.setImageResource(R.mipmap.nitty_right_black)
            }
            "DATE_PICK" -> {//出生日期
                authStepSelectImage.setImageResource(R.mipmap.nitty_right_black)
            }
        }
    }

    /**
     * 联系电话
     */
    private fun showAuthStepContactMobileItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (NittyConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val authStepMobile = helper.getTextView(R.id.authStepMobile)
        authStepMobile.setHint(showHint)
        val authStepMobileEdit = helper.getView<CustomEditText>(R.id.authStepMobileEdit)
        authStepMobileEdit.setHint(showHint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            authStepMobile.text = showValue
            authStepMobileEdit.setText(showValue)
        }
        authStepMobileEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepMobileEdit.clearFocus()
                true
            }
            false
        }
        authStepMobileEdit.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus){
                NittyEventPointHelper.addEventPointRequestAction(String.format(NittyEventPointType.FORM.NITTY_FORM_STEP_INPUT_XX,model.optString("paramName")),authStepMobileEdit.text.toString())
            }
        }
        authStepMobileEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //是否是审核账号
        val isConfigAccount = NittySharedHelper.getNittySharedBoolean(NittySharedKey.NITTY_IS_CONFIG_ACCOUNT)
        if(isConfigAccount){//审核账号 - 允许输入或选择
            authStepMobile.visibility = View.GONE
            authStepMobileEdit.visibility = View.VISIBLE
        } else {//非审核账号只能选择
            authStepMobile.visibility = View.VISIBLE
            authStepMobileEdit.visibility = View.GONE
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}